package com.jiuyin.dianjing.ui.activity.setting;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.SettingBasicInfo;
import com.jiuyin.dianjing.permission.XPermission;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.FileUtils;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.jiuyin.dianjing.view.AlertView;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.SinglePicker;
import de.hdodenhof.circleimageview.CircleImageView;
import me.jessyan.autosize.utils.LogUtils;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ACCOUNT;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_BIRTH;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CLIENTUSER_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_HEADER;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NICK_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SEX;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SIGN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SIGNATURE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.constant.AppConstant.FOLDER_NAME;

/**
 * 个人信息
 */
public class MyPersonalActivity extends BaseActivity {
    private static final int REQUEST_SIGN = 87;
    private static final int REQUEST_NICK_NAME = 88;
    /**
     * 女
     */
    private static final String SEX_FEMALE = "0";
    /**
     * 男
     */
    private static final String SEX_MALE = "1";
    private static final int TAKE_PICTURE = 0;
    private static final int RESULT_LOAD_IMAGE = 1;
    private static final int CUT_PHOTO_REQUEST_CODE = 2;
    @BindView(R.id.img_header)
    public CircleImageView mHeader;
    @BindView(R.id.tv_birth)
    public TextView mBirth;
    @BindView(R.id.tv_sex)
    public TextView mSex;
    @BindView(R.id.tv_mobile)
    public TextView mPhone;
    @BindView(R.id.tv_name)
    public TextView mTvNickname;
    //图片地址
    public String path = "";
    public Uri photoUri;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_sign)
    TextView tvSign;

    private File file;
    private SettingBasicInfo mSettingBasicInfo;
    private String mSign;
    private String mNickName;

    private boolean mChanged;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_my_personal;
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        mSettingBasicInfo = (SettingBasicInfo) bundle.getSerializable(KEY_POST);
    }

    @Override
    protected void initView() {
        setTitle(R.string.my_personal_info);
        if (null != mSettingBasicInfo) {
            Glide.with(this)
                    .load(mSettingBasicInfo.header)
                    .override(DisplayUtil.dp2px(this, 44), DisplayUtil.dp2px(this, 44))
                    .into(mHeader);
            mNickName = mSettingBasicInfo.nickname;
            mTvNickname.setText(mNickName);
            mPhone.setText(mSettingBasicInfo.mobile);
            tvId.setText(mSettingBasicInfo.id);
            String sex = mSettingBasicInfo.sex.equals(SEX_FEMALE) ? getString(R.string.my_sex_female) : getString(R.string.my_sex_male);
            mSex.setText(sex);
            String s = mSettingBasicInfo.birth.contains("T") ?
                    mSettingBasicInfo.birth.substring(0, mSettingBasicInfo.birth.indexOf("T")) : mSettingBasicInfo.birth;
            mBirth.setText(s);
            mSign = mSettingBasicInfo.signature;
        }
    }

    @OnClick({R.id.img_header, R.id.img_header_right, R.id.tv_birth, R.id.tv_sex, R.id.rl_modify_sign, R.id.rl_nick_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_header:
            case R.id.img_header_right:
                selectPhoto();
                break;
            case R.id.tv_birth:
                selectBirth();
                break;
            case R.id.tv_sex:
                selectSex();
                break;
            case R.id.rl_modify_sign: {
                Intent intent = new Intent(this, ModifySignActivity.class);
                intent.putExtra(KEY_SIGN, mSign);
                startActivityForResult(intent, REQUEST_SIGN);
            }
            break;
            case R.id.rl_nick_name: {
                Intent intent = new Intent(this, ModifyNickNameActivity.class);
                intent.putExtra(KEY_NICK_NAME, mNickName);
                startActivityForResult(intent, REQUEST_NICK_NAME);
                break;
            }
        }
    }

    /**
     * 选择生日
     */
    private void selectBirth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar selectedDate = Calendar.getInstance();
        try {
            Date date = format.parse(mBirth.getText().toString());
            selectedDate.setTime(date);
        } catch (ParseException e) {
            selectedDate.setTime(new Date());
        }
        final DatePicker picker = new DatePicker(this);
        picker.setTopPadding(15);
        picker.setRangeStart(1950, 1, 1);
        picker.setRangeEnd(2111, 12, 31);
        picker.setSelectedItem(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH) + 1, selectedDate.get(Calendar.DATE));
        picker.setWeightEnable(true);
        picker.setGravity(Gravity.BOTTOM);
        picker.setLineColor(Color.BLACK);
        picker.setOnDatePickListener((DatePicker.OnYearMonthDayPickListener) (year, month, day) -> {
            if (null != mSettingBasicInfo) {
                SettingBasicInfo temp = new SettingBasicInfo(mSettingBasicInfo);
                temp.birth = year + "-" + month + "-" + day;
                updateUserInfo(temp);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    /**
     * 选择性别
     */
    private void selectSex() {
        ArrayList<String> list = new ArrayList<>();
        list.add(getString(R.string.my_sex_female));
        list.add(getString(R.string.my_sex_male));
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);
        picker.setLineVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(2);
        picker.setGravity(Gravity.BOTTOM);
        picker.setItemWidth(100);
        picker.setOuterLabelEnable(true);
        picker.setSelectedTextColor(Color.GREEN);//前四位值是透明度
        picker.setUnSelectedTextColor(Color.BLACK);
        picker.setOnSingleWheelListener((index, item) -> {
        });
        picker.setOnItemPickListener((index, item) -> {
            if (null != mSettingBasicInfo) {
                SettingBasicInfo temp = new SettingBasicInfo(mSettingBasicInfo);
                temp.sex = index + "";
                updateUserInfo(temp);
            }
        });
        picker.show();
    }

    /**
     * 选择头像
     */
    private void selectPhoto() {
        new AlertView(null, null, "取消", null, new String[]{"从手机相册选择", "拍照"}, this, AlertView.Style.ActionSheet,
                (o, position) -> {
                    if (position == 0) {
                        // 从相册中选择
                        doExternalStoragePermission();
                    } else if (position == 1) {
                        doCameraPermission();
                    }
                }).show();

    }

    private void doExternalStoragePermission() {
        XPermission.requestPermissions(this, 101, new String[]{Manifest.permission
                .WRITE_EXTERNAL_STORAGE}, new XPermission.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                Intent i = new Intent(
                        Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }

            @Override
            public void onPermissionDenied() {
                XPermission.showTipsDialog(MyPersonalActivity.this);
            }
        });
    }

    private void doCameraPermission() {
        XPermission.requestPermissions(this, 101, new String[]{Manifest.permission
                .CAMERA}, new XPermission.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                takePhoto();
            }

            @Override
            public void onPermissionDenied() {
                XPermission.showTipsDialog(MyPersonalActivity.this);
            }
        });
    }

    public void takePhoto() {
        try {
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String sdcardState = Environment.getExternalStorageState();
            String sdcardPathDir = Environment.getExternalStorageDirectory().getPath() + "/tempImage/";
            file = null;
            if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
                // 有sd卡，是否有myImage文件夹
                File fileDir = new File(sdcardPathDir);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                // 是否有headImg文件
                long l = System.currentTimeMillis();
                file = new File(sdcardPathDir + l + ".JPEG");
            }
            if (file != null) {
                path = file.getPath();

                photoUri = Uri.fromFile(file);
                if (Build.VERSION.SDK_INT >= 24) {
                    photoUri = FileProvider.getUriForFile(this, getString(R.string.file_provider_authorities), file);
                } else {
                    photoUri = Uri.fromFile(file);
                }
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        boolean ret = resultCode == RESULT_OK;
        LogUtil.printIntent(data);
        switch (requestCode) {
            case TAKE_PICTURE:
                if (file != null && file.exists())
                    startPhotoZoom(photoUri);
                break;
            case RESULT_LOAD_IMAGE:
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        startPhotoZoom(uri);
                    }
                }
                break;
            case CUT_PHOTO_REQUEST_CODE:
                if (ret && null != data) {// 裁剪返回
                    if (path != null && path.length() != 0) {
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        //给头像设置图片源
                        mHeader.setImageBitmap(bitmap);
                        //上传头像
                        OSSCompletedCallback<PutObjectRequest, PutObjectResult> userCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                if (null != mSettingBasicInfo) {
                                    SettingBasicInfo temp = new SettingBasicInfo(mSettingBasicInfo);
                                    temp.header = "http://jiuyinesports.com/" + request.getObjectKey();
                                    runOnUiThread(() -> updateUserInfo(temp));
                                }
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                ToastUtil.showShort(clientException.getMessage());
                            }
                        };
                        String fileName = FileUtils.generateFileName(path);
                        HelperApplication.ossService.asyncPutImage(FOLDER_NAME + fileName, path, userCallback, null);
                    }
                }
                break;
            case REQUEST_SIGN: {
                if (data == null) {
                    return;
                }
                if (null != mSettingBasicInfo) {
                    String sign = data.getStringExtra(KEY_SIGN);
                    SettingBasicInfo temp = new SettingBasicInfo(mSettingBasicInfo);
                    temp.signature = sign;
                    updateUserInfo(temp);
                }
                break;
            }
            case REQUEST_NICK_NAME: {
                if (data == null) {
                    return;
                }
                if (null != mSettingBasicInfo) {
                    String nickname = data.getStringExtra(KEY_NICK_NAME);
                    SettingBasicInfo temp = new SettingBasicInfo(mSettingBasicInfo);
                    temp.nickname = nickname;
                    updateUserInfo(temp);
                }
                break;
            }
        }
    }

    private void updateUserInfo(SettingBasicInfo temp) {
        if (temp.sex.equals(mSettingBasicInfo.sex) && temp.header.equals(mSettingBasicInfo.header)
                && temp.birth.equals(mSettingBasicInfo.birth) && temp.nickname.equals(mSettingBasicInfo.nickname) && temp.signature.equals(mSettingBasicInfo.signature)) {
            return;
        }
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_HEADER, temp.header);
        hashMap.put(KEY_NICK_NAME, temp.nickname);
        hashMap.put(KEY_SEX, temp.sex);
        hashMap.put(KEY_BIRTH, temp.birth);
        hashMap.put(KEY_SIGNATURE, temp.signature);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());

        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                LogUtil.log("onSuccess " + data.toString());
                mChanged = true;
                mSettingBasicInfo = new SettingBasicInfo(temp);
                mSettingBasicInfo.nickname = data.get(KEY_NICK_NAME).getAsString();
                mSettingBasicInfo.birth = data.get(KEY_BIRTH).getAsString();
                mSettingBasicInfo.sex = data.get(KEY_SEX).getAsString();
                mSettingBasicInfo.header = data.get(KEY_HEADER).getAsString();
                mSettingBasicInfo.mobile = data.get(KEY_ACCOUNT).getAsString();
                if (data.has(KEY_SIGNATURE)) {
                    mSettingBasicInfo.signature = data.get(KEY_SIGNATURE).getAsString();
                }
                HelperApplication.setUserId(data.get(KEY_CLIENTUSER_ID).getAsString());
                HelperApplication.setNickName(mSettingBasicInfo.nickname);
                HelperApplication.setHeader(mSettingBasicInfo.header);
                HelperApplication.setMobile(mSettingBasicInfo.mobile);
                initView();
            }
        };
        ServerApi.post(ApiEnum.APP_UPDATE_USER_API.getUrl(), data, null, progress, d -> addDisposable(d), requestCallback);
    }

    private void startPhotoZoom(Uri uri) {
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String address = sDateFormat.format(new Date());
            if (!FileUtils.isFileExist("")) {
                FileUtils.createSDDir("");
            }

            Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");
            final Intent intent = new Intent("com.android.camera.action.CROP");

            // 照片URL地址
            intent.setDataAndType(uri, "image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 480);
            intent.putExtra("outputY", 480);
            // 输出路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 输出格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            // 不启用人脸识别
            path = FileUtils.SDPATH + address + ".JPEG";
            intent.putExtra("noFaceDetection", false);
            intent.putExtra("return-data", false);
            intent.putExtra("fileurl", path);
            startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);
        } catch (IOException e) {
            LogUtils.w(e.getMessage());
        }
    }

    @Override
    public void onBackPressed() {
        if (mChanged) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }
}
